from tornado.websocket import WebSocketHandler
import json
class ChessMsg(WebSocketHandler):
    users = set() # 用来存放在线用户的容器
    chessBoardMap=[]
    chessInfo={}
    chess_type1=[["帅",0],["仕",2],["相",4],["马",6],["车",8],["炮",10],["兵",15]]
    chess_type2=[["将",0],["士",2],["象",4],["马",6],["车",8],["炮",10],["卒",15]]

    def init_chess(self,msg):
        data=[]
        before=-1
        for i in range(16):
            for item in self.chess_type1:
                is_true=before<i<=item[1]
                if i<=8 and is_true:
                    data.append({"id":len(data),"t":item[0],"y":0})
                    data[-1]["x"]=4 + (int((i+1)/2) if i%2 else -int((i+1)/2))
                    before=i
                    break
                elif 8<i<=10 and is_true: #炮
                    data.append({"id":len(data),"t":item[0],"y":2})
                    data[-1]["x"]=1 if i==9 else 7
                    before=i
                    break
                elif i>10 and is_true:
                    data.append({"id":len(data),"t":item[0],"y":3})
                    data[-1]["x"]=(i-11)*2
                    before=i
                    break
        before=-1
        for i in range(16):
            for item in self.chess_type2:
                is_true=before<i<=item[1]
                if i<=8 and is_true:
                    data.append({"id":len(data),"t":item[0],"y":9})
                    data[-1]["x"]=4 + (int((i+1)/2) if i%2 else -int((i+1)/2))
                    before=i
                    break
                elif 8<i<=10 and is_true: #炮
                    data.append({"id":len(data),"t":item[0],"y":7})
                    data[-1]["x"]=1 if i==9 else 7
                    before=i
                    break
                elif i>10 and is_true:
                    data.append({"id":len(data),"t":item[0],"y":6})
                    data[-1]["x"]=(i-11)*2
                    before=i
                    break
        return "all",data

    def init_board(self,msg):
        ChessMsg.chessInfo={
            "groupId":1, #红方 0 为锁定状态
            "step1":0, #红方
            "step2":0, #黑方
            "win":None, #赢
        }
        data=[]
        for y in range(10):
            row=[None for x in range(9)]
            data.append(row)
        _,chess_list=self.init_chess(msg)
        chess_map={}
        for r in chess_list:
            data[r["y"]][r["x"]]=r["id"]
            chess_map[r["id"]]=r["t"]
        ChessMsg.chessBoardMap=data
        return "all",{"board":data,"chessMap":chess_map,"chessInfo":ChessMsg.chessInfo}

    def get_board(self,msg):
        if len(ChessMsg.chessBoardMap)==0:
            self.init_board(msg)
        _,chess_list=self.init_chess(msg)
        chess_map={}
        for r in chess_list:
            chess_map[r["id"]]=r["t"]
        return "user",{"board":ChessMsg.chessBoardMap,"chessMap":chess_map,"chessInfo":ChessMsg.chessInfo}

    def select_chess(self,msg):
        return "all",msg

    def move_chess(self,msg):
        fr=msg["from"]
        to=msg["to"]
        if fr["x"]!=to["x"] or fr["y"]!=to["y"]:
            if to["id"] is None or ((int(fr["id"])<16) !=  (int(to["id"])<16)):
                ChessMsg.chessBoardMap[to["y"]][to["x"]]=fr["id"]
                ChessMsg.chessBoardMap[fr["y"]][fr["x"]]=None
                if int(fr["id"])<16:
                    ChessMsg.chessInfo["step1"]+=1
                    ChessMsg.chessInfo["groupId"]=2
                else:
                    ChessMsg.chessInfo["step2"]+=1
                    ChessMsg.chessInfo["groupId"]=1
                if (not to["id"] is None) and int(to["id"]) in [0,16]: #赢棋情况
                    ChessMsg.chessInfo["win"]="红方获胜" if int(to["id"])==16 else "黑方获胜"
                    ChessMsg.chessInfo["groupId"]=0
        
        msg["chessInfo"]=ChessMsg.chessInfo
        return "all",msg

    def send(self,msg):
        json_msg=json.dumps(msg)
        if msg["scope"]=="user":
            self.write_message(json_msg)
            return
        elif msg["scope"]=="other_user" and "userId" in msg: #非自己
            for u in self.users:
                if str(msg["userId"])==str(u.userId):
                    continue
                u.write_message(json_msg)
        if msg["scope"]=="all":
            for u in self.users:
                u.write_message(json_msg)

    def open(self):
        self.userId=len(self.users)
        ChessMsg.users.add(self)
        for u in self.users:
            u.write_message(json.dumps({"type":"join","scope":"all","userId":u.userId,"joinUserId":self.userId,"userCount":len(self.users)}))

    def on_message(self, message):
        msg=json.loads(message)
        msg_type=msg["type"]
        if hasattr(self,msg_type) :
            result_type,data=getattr(self,msg_type)(msg)
            data["type"]="re_"+msg_type
            data["scope"]=result_type
            self.send(data)
        else:
            print("不支持的类型%s"%(msg_type))

    def on_close(self):
        currentId=self.userId
        self.users.remove(self) # 用户关闭连接后从容器中移除用户
        self.send({"type":"exit","scope":"all","userId":currentId})

    def check_origin(self, origin):
        return True  # 允许WebSocket的跨域请求
